package edu.gyc.hisecurity.auth;

import edu.gyc.hisecurity.service.UserService;
import edu.gyc.hisecurity.validate.ValidateCodeFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Autowired
    private MyFilterSecuritySource securitySource;

    @Autowired
    private MyAccessDecisionManager accessManager;

    @Bean
   public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 忽略拦截url或静态资源文件夹 - web.ignoring(): 会直接过滤该url - 将不会经过Spring Security过滤器链
     *                             http.permitAll(): 不会绕开springsecurity验证，相当于是允许该路径通过
     * @param web
     * @throws Exception
     */

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.GET,"/**/*.js","/**/*.css","/layui/**","/img/**"
        ,"/user/image");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
      /**  auth.inMemoryAuthentication()
                .withUser("zyj")
                .password("123")
                .roles("admin")
                .and()
                .withUser("周慧敏")
                .password("123")
                .roles("lover");
       */
      auth.userDetailsService(userService);
    }

    @Bean
    RoleHierarchy roleHierarchy() { //角色继承，ROLE_dba > ROLE_admin dba权限大于admin
        RoleHierarchyImpl roleHierarchy=new RoleHierarchyImpl();
        String hierarchy = "ROLE_dba > ROLE_admin \n ROLE_admin > ROLE_user";
        roleHierarchy.setHierarchy(hierarchy);
        return roleHierarchy;
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ValidateCodeFilter  validateCodeFilter=new ValidateCodeFilter();


        http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class);

               http. authorizeRequests()
             //   .antMatchers("/index").permitAll()
             //   .antMatchers("/user/image","/my/user/hi").permitAll()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O object) {

                        object.setSecurityMetadataSource(securitySource);
                        object.setAccessDecisionManager(accessManager);
                        return object;
                    }
                })

                .anyRequest().authenticated()

                .and()

                .formLogin()

                .loginPage("/index")
                .loginProcessingUrl("/doLogin")
                .successForwardUrl("/getUserMenus")
                .permitAll()
                .and()
                .logout()
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                       /*
                        response.setContentType("application/json;charset=utf-8");
                        PrintWriter out=response.getWriter();
                        ResultBean resultBean = new ResultBean(200, "注销成功");
                        out.write(new ObjectMapper().writeValueAsString(resultBean));
                        out.flush();
                        out.close();

                        */
                       response.sendRedirect("exit");
                    }
                })
                //解决Refused to display '' in a frame because it set 'X-Frame-Options' to 'deny'
                .and().headers().frameOptions().sameOrigin()
                .and()
                .csrf().disable()
                 ;
    }
}
